console.info('contentScript is running')
import {
  getItem,
  setItem,
  startTyping,
  innReqParams
} from '../utils'
import captureFullPageWithHtml2Canvas from '../utils/screenshot';
import { teamType } from '../config/index'

// 添加文本选择监听器
const addSelectionListener = () => {
  // 监听mouseup事件
  document.addEventListener('mouseup', () => {
    const selectedText = window.getSelection()?.toString();
    if (selectedText) {
      // 发送选中的文本到后台
      chrome.runtime.sendMessage({ action: 'selectedText', data: selectedText });
    }
  }
  );
};

addSelectionListener();

let isSelecting = false;
chrome.runtime.onMessage.addListener(async function (request) {
  console.log('request content: ', request);
  if (request.action === 'simulateTyping') {
    startTyping();
  } else if (request.action === 'screenshot') {
    captureFullPageWithHtml2Canvas();
  } else if (request.action === 'getSelectedText') {
    const selectedText = window.getSelection()?.toString().trim();
    if (selectedText) {
      // 发送选中的文本到后台
      getItem('kkNote').then((result: any) => {
        if (result) {
          const kkNote = `${result}\n${selectedText}`;
          setItem('kkNote', kkNote)
        }else{
          const kkNote = `${selectedText}`;
          setItem('kkNote', kkNote)
        }
        chrome.runtime.sendMessage({ action: 'selectedTextAddNote', data: selectedText });
      })
    }
  } else if (request.action === 'simulateTypingZipCode') {
    getItem('ipinfo').then((value: any) => {
      if (value) {
        if (value.ip_data) {
          let zipcode = value.ip_data.zipcode;
          navigator.clipboard
            .writeText(zipcode)
            .then(function () {
              console.log('Zipcode copied to clipboard');
              startTyping();
            })
            .catch(function () {
              console.error('Failed to copy zipcode to clipboard');
            });
        }
      }
    });
  }else if (request.action === "copy_text_under_mouse") {
    handleCopyFromLastClickedElement();
  }else if (request.action === "inn_check_detail") {
    let url: any = await getItem('innovatemrDetail')
    if (!url) return
    fetch(url, innReqParams)
      .then((response) => response.json())
      .then((data) => {
        localStorage.setItem('inn_detail', JSON.stringify(data))
        if (data.status === 'Success') {
          setItem('inn_detail', data)
          if (data.data.termReason || data.data.termReasonDetails) {
            const reason =
              data.data.termReasonDetails.length > 0
                ? data.data.termReasonDetails
                : data.data.termReason;
                  showAuthorizationWarning(
                    `${reason.toString()}`,
                  );
          }
        }
      })
      .catch((error) => {
        console.error('Error fetching data:', error)
      })
  } else if (request.action === "get_question") {
    const h5Element2 = document.querySelector('h5.question-text')
      if (h5Element2) {
        let body = {
          question: h5Element2.textContent,
          ...request.data
        }
        chrome.runtime.sendMessage({ action: 'report_question', data: body });
      }
  }
});

function showAuthorizationWarning(content: any) {
      const warningBox: any = document.createElement('div');
      warningBox.style =
        'position:fixed;top:20px;left:20px;background:black;color:white;padding:20px;z-index:9999';
      warningBox.innerHTML = `
        <h3>Term Reason Details</h3>
        <p>${content} </p>
      `;
      document.body.appendChild(warningBox);
}


let checkTimer: any = null
let currentTime = 0
let maxTime = 60 * 1000 // 30秒
function checkLoading() {
  console.log('checkLoading: ');
  clearInterval(checkTimer)
  checkTimer = setInterval(() => {
    currentTime += 1000
    if (currentTime >= maxTime) {
      clearInterval(checkTimer)
    }
    const loadingElement = document.querySelector('.mat-mdc-progress-spinner')
    if (!loadingElement) {
      setTimeout(() => {
        realTimeCheckLoading()
      }, 1000)
      clearInterval(checkTimer)
    } else {
      const h5Element2 = document.querySelector('h5.question-text')
      if (h5Element2) {
        setTimeout(() => {
          realTimeCheckLoading()
        }, 1000)
        clearInterval(checkTimer)
      }
    }
  }, 1000)
}

function realTimeCheckLoading() {
  // 创建自定义按钮并设置事件监听器
  function createCustomButton(h5Element: any) {
    const rect = h5Element.getBoundingClientRect()
    const endX = rect.right
    const endY = rect.top

    const customElement = document.createElement('button')
    customElement.style.position = 'absolute'
    customElement.style.left = `${endX}px`
    customElement.style.top = `${endY}px`
    customElement.textContent = 'AUTO'
    customElement.style.backgroundColor = '#007BFF'
    customElement.style.color = 'white'
    customElement.style.border = 'none'
    customElement.style.padding = '6px 10px'
    customElement.style.borderRadius = '5px'
    customElement.style.fontSize = '16px'
    customElement.style.cursor = 'pointer'
    customElement.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.2)'

    customElement.addEventListener('mouseover', () => {
      customElement.style.backgroundColor = '#0056b3'
    })
    customElement.addEventListener('mouseout', () => {
      customElement.style.backgroundColor = '#007BFF'
    })

    customElement.addEventListener('click', async () => {
      customElement.textContent = 'Loading...'
      customElement.disabled = true
      const h5Element2: any = document.querySelector('h5.question-text')
      chrome.runtime.sendMessage(
        {
          action: 'CREATE_MESSAGE_FLOAT_QUICK',
          data: h5Element2.textContent,
        },
        async function (response) {
          customElement.disabled = false
          customElement.textContent = 'AUTO'

          if (chrome.runtime.lastError) {
            alert(`消息发送出错: ${chrome.runtime.lastError.message}`)
            return
          }

          if (response && response.status && response.msg.code === 0) {
            const textarea: any = document.querySelector('textarea[name="selectedOptField"]')
            if (textarea) {
              textarea.value = ''
              try {
                textarea.focus()

                const text = response.msg.data
                // 第一步：整体清理文本，去除开头/结尾的符号和空白
                const cleanedText = text.replace(/^[-—_\s]+|[-—_\s]+$/g, '')

                // 第二步：用'---'分割，清理每部分并过滤空字符串
                const trimmedParts = cleanedText
                  .split('---')
                  .map((part: string) => part.trim())
                  .filter((part: string) => part.length > 0)

                if (trimmedParts.length === 0) return null

                // 第三步：随机选择一部分
                const randomIndex = Math.floor(Math.random() * trimmedParts.length)
                const randomPart = trimmedParts[randomIndex]
                await startTyping(randomPart)
              } catch (clipboardErr: any) {
                alert(`复制到剪贴板出错: ${clipboardErr.message}`)
              }
            }
          } else {
            alert(`ERROR ${response?.msg?.msg || response?.msg}`)
          }
        },
      )
    })

    return customElement
  }

  const h5Element = document.querySelector('h5.question-text')
  if (h5Element) {
    const customElement = createCustomButton(h5Element)
    document.body.appendChild(customElement)

    window.addEventListener('resize', () => {
      const updatedH5Element = document.querySelector('h5.question-text')
      if (updatedH5Element) {
        const updatedRect = updatedH5Element.getBoundingClientRect()
        const updatedLeft = updatedRect.right
        const updatedTop = updatedRect.top
        customElement.style.left = `${updatedLeft}px`
        customElement.style.top = `${updatedTop}px`
      }
    })
  }
}


if (teamType === 'buer') {
  if (
    location.href.includes('edgesurvey.innovatemr.net/survey/qualitative_questions') ||
    location.href.includes('edgesurvey.innovatemr.net/survey/text_analyze') ||
    location.href.includes('edgesurvey.innovatemr.net/survey/red_herring')
  ) {
    // 调用方法开始实时检测
    checkLoading()
  }
}

// ======= 工具函数 ======= //
function copyTextToClipboard(text: any) {
  if (!text) return;
  navigator.clipboard.writeText(text).then(() => {
    showToast('✅ Get success');
  }).catch(err => {
    showToast('❌ Get failed');
  });
}

let toastContainer: any = null;

function showToast(message: any) {
  chrome.runtime.sendMessage({ action: 'show_notification', data: message });
}


// ======= 主逻辑 ======= //
// 按住Alt+鼠标点击，复制被点击元素的文本
document.addEventListener('mousedown', (event) => {
  if (!event.target) return;
  const target = event.target as HTMLElement;

  // 获取元素文本的统一方法
  const getTextFromElement = (el: HTMLElement): string => {
    if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
      return el.value.trim();
    }
    return (el.innerText || el.textContent || '').trim();
  };

  const cleanedText = getTextFromElement(target);

  // Alt键：复制文字
  if (event.altKey) {
    if (cleanedText) {
      chrome.runtime.sendMessage({ action: 'selectedTextAll', data: cleanedText });
      copyTextToClipboard(cleanedText);
    } else {
      showToast('⚠️ current element has no text');
    }
  }

  // Shift键：添加到记事本
  if (event.shiftKey) {
    if (cleanedText) {
      getItem('kkNote').then((result: any) => {
        const kkNote = result ? `${result}\n${cleanedText}` : cleanedText;
        setItem('kkNote', kkNote);
        chrome.runtime.sendMessage({ action: 'selectedTextAddNote', data: cleanedText });
        showToast('✅ Add note success');
      });
    }
  }

  lastClickedElement = target;
});

let lastClickedElement:any = null;
// 封装的方法：复制上一次点击的元素内容
function handleCopyFromLastClickedElement() {
  if (!lastClickedElement) {
    showToast('⚠️ please click an element first');
    return;
  }

  let textToCopy = '';

  // 针对不同元素分类处理
  if (lastClickedElement instanceof HTMLInputElement || lastClickedElement instanceof HTMLTextAreaElement) {
    textToCopy = lastClickedElement.value || '';
  } else {
    textToCopy = lastClickedElement.innerText || lastClickedElement.textContent || '';
  }

  const cleanedText = textToCopy.trim();

  if (cleanedText) {
    navigator.clipboard.writeText(cleanedText)
      .then(() => {
        showToast('✅ copy success');
      })
      .catch((err) => {
        showToast('❌ copy failed');
      });
  } else {
    showToast('⚠️ current element has no text');
  }
}
